package com.kdg.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by kong on 2017/8/10.
 * 线程通信   Condition
 * 利用相应的Condition和Lock之间的配合控制线程通信(也可通过控制指定的Condition唤醒所指定的线程)
 */

public class TestCondition{
    public static void main(String[] args) {
        ConditionTest testCondition = new ConditionTest();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<5;i++){
                    testCondition.loopA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<5;i++){
                    testCondition.loopB();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<5;i++){
                    testCondition.loopC();
                }
            }
        }).start();
    }

}
class ConditionTest {

    private int number = 3;

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void loopA() {
        lock.lock();
        try {
            if(number != 1){
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"A");
            number = 3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }
    public void loopB() {
        lock.lock();
        try {
            if(number != 2){
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"B");
            number = 1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
    public void loopC() {
        lock.lock();
        try {
            if(number != 3){
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"C");
            number = 2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }
}

